// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class GamerScript extends cc.Component {

    @property(cc.AudioClip)
    audio : cc.AudioClip = null

    @property(cc.SpriteFrame)
    moveLeftSpriteFrame : cc.SpriteFrame = null

    @property(cc.SpriteFrame)
    moveRightSpriteFrame : cc.SpriteFrame = null

    @property("number")
    step : number = 20
    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.keyDownForMove, this)
    }

    moveLeft() {
        let gamerSprite : cc.Sprite = cc.find("Canvas/Gamer/toward").getComponent(cc.Sprite)
        if(this.moveLeftSpriteFrame !== null) gamerSprite.spriteFrame = this.moveLeftSpriteFrame
        this.node.x -= 20
        if(this.audio !== null) cc.audioEngine.play(this.audio, false, 1)
    }

    moveRight() {
        let gamerSprite : cc.Sprite = cc.find("Canvas/Gamer/toward").getComponent(cc.Sprite)
        if(this.moveRightSpriteFrame !== null) gamerSprite.spriteFrame = this.moveRightSpriteFrame
        this.node.x += 20
        if(this.audio !== null) cc.audioEngine.play(this.audio, false, 1)
    }

    keyDownForMove(evt) {
        if(evt.keyCode === 37) {
            this.moveLeft()
        } else if(evt.keyCode === 39) {
            this.moveRight()
        }
    }
}
